package javango.middleware;

import javango.core.AnonymousUser;
import javango.http.HttpRequest;
import javango.http.HttpResponse;
import javango.http.HttpResponseRedirect;
import javango.http.SimpleHttpResponse;

/**
 * Basic {@link Middleware} class that forces a trailing slash ('/') for all urls and adds an {@link AnonymousUser} to the request
 * if request.getUser() returns null
 * 
 * @author johns
 *
 */
public class CommonMiddleware extends Middleware {

	@Override
	public HttpResponse processRequest(HttpRequest request) {

		String path = request.getPath();
		if (path.length() > 0 && !path.endsWith("/")) {
			if ("POST".equals(request.getMethod())) {
				return new SimpleHttpResponse("Cannot append trailing slash to POSTed you should update the form.");
			}
			path = request.getContext() + "/" + path + "/";
			return new HttpResponseRedirect(path);
		}
		
		if (request.getUser() == null) {
			request.setUser(new AnonymousUser());
		}
		return super.processRequest(request);
	}

}
